package servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;

@WebServlet(urlPatterns = "/downing")
public class DownServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        String fileName = req.getParameter("filename");
        String path = "/uploadfiles/"+fileName;
        // 设置响应的类型，将响应的内容设置为通用的二进制流
        resp.setContentType("application/octet-stream");
        // 如果文件名包含汉字，页面显示文件名会有乱码，可以将文件名转换为UTF-8编码下的字符串
        fileName = URLEncoder.encode(fileName, "UTF-8");
        // 设置响应的头信息，attachment:告诉浏览器以附件的方式下载文件（弹出下载框）
        resp.addHeader("Content-Disposition","attachment;filename="+fileName);
        // 跳转页面
        req.getRequestDispatcher(path).forward(req,resp);
        // 清空缓冲区
        resp.flushBuffer();
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
